package com.esyoga.yoyoga.handler;

import com.esyoga.yoyoga.enums.UserTypeEn;
import com.esyoga.yoyoga.pojo.DTO.TtrainerAgreementDTO;
import com.esyoga.yoyoga.pojo.TGym;
import com.esyoga.yoyoga.pojo.TStudent;
import com.esyoga.yoyoga.pojo.TTrainer;
import com.esyoga.yoyoga.pojo.TTrainerAgreement;
import com.esyoga.yoyoga.service.AgreementService;
import com.esyoga.yoyoga.service.TrainerService;
import com.esyoga.yoyoga.util.CutPagesUtil;
import com.esyoga.yoyoga.util.DateFormatUtil;
import com.esyoga.yoyoga.util.TrainerTimeUtil;
import lombok.Data;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Data
@Controller
@RequestMapping("/trainer")
public class TrainerHandler {
    @Resource
    TrainerService trainerService;
    @Resource
    AgreementService agreementService;

    /**
     * 通过合约状态和教练id查出所有该状态下的学生
     * @param cState   合约状态信息
     * @param tId       教练id
     * @return
     */
    @RequestMapping("/getStudentsByGaStateAndTid")
    @ResponseBody
    public List<TStudent> getStudentsByCStateAndTid(int cState, int tId){
        List<TStudent> students = trainerService.getStudentsByCStateAndTid(cState,tId);
        System.out.println(students);
        return students;
    }

    /**
     * 通过教练的id获取教练空闲时间的MAP
     * @param tId
     * @return
     */
    @RequestMapping("/getTrainerTimeInfo")
    @ResponseBody
    public Map<String,String> getTrainerTimeInfo(int tId){
//        System.out.println(1111111);
        TTrainer trainer = trainerService.selectTrainerById(tId);
        String freeTime = trainer.gettFreetime();
        return TrainerTimeUtil.getTimeMapInfoByTimeString(freeTime);
    }

    /**
     * 到指定教练的页面
     * @param tId 教练ID
     * @param gId 场馆ID 如果上一页面是场馆页面的话，则会传入场馆ID
     * @return
     */
    @RequestMapping("/singleTrainer")
    @ResponseBody
    public ModelAndView goTrainerInfoPape(Integer tId, Integer gId){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("trainerInfo",trainerService.selectTrainerById(tId));
        modelAndView.addObject("gymList",trainerService.selectGymBytId(tId));
        if(gId!=null){
            modelAndView.addObject("gId",gId);
        }
        modelAndView.setViewName("html/singleTrainer.html");
        return modelAndView;
    }

    //教练信息展示(分页显示)
    @RequestMapping("/findAllTrainers")
    @ResponseBody
    public Map<String,Object> findAllTrainers(Integer page, @RequestParam(value ="tName",required = false,defaultValue = "")String tName) {
        //设置查找范围，page：查询的页码，pageSize:显示条数
        //PageHelper.startPage(page, 2);
        // System.out.println(page);

        //设置模糊查询
        tName = "%" + tName + "%";
        //根据场馆的名字进行模糊查询,获得场馆集合
        List<TTrainer> trainers=trainerService.selectTrainers(tName);
        CutPagesUtil.clear();
        CutPagesUtil.setPageInfo(page,10);
        List<TTrainer> trainerList = CutPagesUtil.getPages(trainers);
        int total = CutPagesUtil.getTotalPage();
        Map<String,Object> result=new HashMap<String,Object>();
        result.put("total",total);
        result.put("currentMessage",trainerList);
        return result;
    }

    /**
     * 根据tId查找正在教练签约中的场馆
     * @param tId
     * @return
     */
    @RequestMapping("/selectGymBytId")
    @ResponseBody
    public List<TGym> selectGymBytId(Integer tId){
        return trainerService.selectGymBytId(tId);
    }


    /**
     * 根据教练与场馆签订的合同信息：t_trainer_agreement表，教练场馆之间
     * @param aState 合同状态
     * @return
     */
    @RequestMapping("/selectAgreement")
    @ResponseBody
    public Map<String, Object> selectTrainersByStuId(HttpServletRequest request, Integer page, int aState){
        Map<String, Object> result =new HashMap<>();

        Object obj = request.getSession().getAttribute("user");
        UserTypeEn userTypeEn = (UserTypeEn) request.getSession().getAttribute("userTypeEn");
        if(obj==null||userTypeEn==null)return null;
        List<TTrainerAgreement> tTrainerAgreements;

        //查询教练与场馆签订的合同
        switch (userTypeEn){
            case TRAINER:
                TTrainer trainer = (TTrainer) obj;
                Integer tId = trainer.gettId();
                tTrainerAgreements = agreementService.selectAgreementBytIdAndaState(tId,aState);
                break;
            default:
                return null;
        }
        //分页
        CutPagesUtil.clear();
        CutPagesUtil.setPageInfo(page,10);
        List<TTrainerAgreement> trainerAgreementList = CutPagesUtil.getPages(tTrainerAgreements);
        //得到DTO的数据
        List<TtrainerAgreementDTO> trainerAgreementDTOList = agreementService.selectTrainerAgreementDTO(trainerAgreementList);
        int total = CutPagesUtil.getTotalPage();
        result.put("total",total);
        result.put("currentMessage",trainerAgreementDTOList);
        return result;
    }


    /**
     * 创建场馆和教练签订的合同
     * @param gId
     * @return
     */
    @PostMapping("/createTrainerGymAgreement")
    @ResponseBody
    public Map<String, Object> createContract(HttpServletRequest request, Integer gId ){
        //Todo:判断是否已经有未终止合约，先来不及写了

        Map<String, Object> result =new HashMap<>();
        result.put("result", "fail");

        Object obj = request.getSession().getAttribute("user");
        UserTypeEn userTypeEn = (UserTypeEn) request.getSession().getAttribute("userTypeEn");
        if(obj==null||userTypeEn==null){
            result.put("reason","缺少参数");
            return result;
        }
        Integer tId;
        switch (userTypeEn){
            case TRAINER:
                TTrainer trainer = (TTrainer)obj;
                tId = trainer.gettId();
                List<Integer> stateList = new ArrayList<>();
                stateList.add(0);
                stateList.add(1);
                stateList.add(4);
                List<TTrainerAgreement> lis = agreementService.selectByGIdAndTIdOnGoing(gId,tId,stateList);
                if(lis!=null&&lis.size()!=0){
                    result.put("reason","请勿重复发起");
                    return result;
                }
                break;
            default:
                return result;
        }
        TTrainerAgreement trainerAgreement = new TTrainerAgreement();
        trainerAgreement.setTaTId(tId);
        trainerAgreement.setTaGId(gId);
        trainerAgreement.setTaGymratio(0.1);//todo:场馆ID查询场馆抽成比例,暂时写死
        trainerAgreement.setTaState(0);//教练发起的初始状态
        trainerAgreement.setTaCreatetime(DateFormatUtil.getCurrentDateString());
        trainerAgreement.setTaUpdatetime(DateFormatUtil.getCurrentDateString());
        //设置
        if(agreementService.insertTrainerAgreement(trainerAgreement)<0){
            result.put("reason","服务器错误，请重试");
            return result;
        }else {
            result.put("result","success");
            return result;
        }
    }

    /**
     * 查找当前登陆的教练和与指定场馆正在进行中的合约
     * 正在进行中指的是0,1,4状态
     * @param gId
     * @return
     */
    @ResponseBody
    @RequestMapping("/ongoingAgreement")
    public TTrainerAgreement selectTrainerAgreementOnging(HttpServletRequest request, Integer gId){
        Object obj = request.getSession().getAttribute("user");
        UserTypeEn userTypeEn = (UserTypeEn) request.getSession().getAttribute("userTypeEn");
        if(obj==null||userTypeEn==null)return null;
        List<Integer> stateList = new ArrayList<>();
        stateList.add(0);
        stateList.add(1);
        stateList.add(4);

        //查询教练与场馆签订的合同
        switch (userTypeEn){
            case TRAINER:
                TTrainer trainer = (TTrainer) obj;
                Integer tId = trainer.gettId();
                List<TTrainerAgreement> lis = agreementService.selectByGIdAndTIdOnGoing(gId,tId,stateList);
                if(lis!=null&&lis.size()!=0){
                    //业务逻辑是教练和场馆同一时刻只能有一个未终止的合约
                    TTrainerAgreement trainerAgreement =lis.get(0);
                    return trainerAgreement;
                }else{
                    return null;
                }
            default:
                return null;
        }
    }

}
